import { queryServiceList,delServiceList, synApiCacheToDb, synApiDbToCache, delCache } from '../services/service';

export default {
    namespace: 'service',

    state: {
        data: {
            list: [],
            pagination: {},
        },
        serviceList: [],
        loading: true,
    },
    effects: {
        * fetch({payload}, {call, put}) {
            yield put({
                type: 'changeLoading',
                payload: true,
            });
            const response = yield call(queryServiceList, payload);
            yield put({
                type: 'save',
                payload: response,
            });
            yield put({
                type: 'changeLoading',
                payload: false,
            });
        },
        * del({payload, callback}, {call, put}) {
            yield put({
                type: 'changeLoading',
                payload: true,
            });
            const response = yield call(delServiceList, payload);
            yield put({
                type: 'changeLoading',
                payload: false,
            });

            if (callback) callback(response);
        },
        * synApiCacheToDb({payload, callback}, {call, put}) {
            yield put({
                type: 'changeLoading',
                payload: true,
            });
            const response = yield call(synApiCacheToDb, payload);
            yield put({
                type: 'changeLoading',
                payload: false,
            });

            if (callback) callback(response);
        },
        * synApiDbToCache ({payload, callback},{call, put}){
            yield put({
                type: 'changeLoading',
                payload: true,
            });
            const response = yield call(synApiDbToCache, payload);
            yield put({
                type: 'changeLoading',
                payload: false,
            });

            if (callback) callback(response);
        },
        * delCache ({payload, callback}, {call, put}){
            yield put({
                type: 'changeLoading',
                payload: true,
            });
            const response = yield call(delCache, payload);
            yield put({
                type: 'changeLoading',
                payload: false,
            });

            if (callback) callback(response);
        }
    },

    reducers: {
        save(state, action) {
            return {
                ...state,
                data: action.payload.resultData.serviceList,
            };
        },

        changeLoading(state, action) {
            return {
                ...state,
                loading: action.payload,
            };
        },

    },
};
